package org.zhc.context;

import java.util.HashMap;
import java.util.Map;

import org.zhc.exception.NoActionDefinedException;
import org.zhc.po.Action;
import org.zhc.po.HttpContext;


public class ActionContext {

	private static Map<String, Map<String, Action>> actions = new HashMap<String, Map<String, Action>>();
	private static Map<Object, HttpContext> httpContexts = new HashMap<Object, HttpContext>();
	private static String basePath;
	private static String filePath;

	public static void initApplicationBasePath(String basePath) {
		ActionContext.basePath = basePath;
	}

	public static void initApplicationFilePath(String filePath) {
		if(!filePath.endsWith(System.getProperty("file.separator"))){
			filePath +=System.getProperty("file.separator");
		}
		ActionContext.filePath = filePath;
	}

	public static void addNamespace(String namespace,
			Map<String, Action> actions) {
		if (namespace != null) {
			ActionContext.actions.put(namespace, actions);
		}
	}

	public static Action findAction(String namespace, String actionname)
			throws NoActionDefinedException {
		Map<String, Action> nsActions = ActionContext.actions.get(namespace);
		if (nsActions != null) {
			Action action = nsActions.get(actionname);
			if (action != null) {
				return action;
			}
			throw new NoActionDefinedException("No Action " + actionname
					+ ".action defined in namespace \"" + namespace + "\".");
		}
		throw new NoActionDefinedException("No Action " + actionname
				+ ".action defined in namespace \"" + namespace + "\".");
	}

	public static void addContext(Object obj, HttpContext httpContext) {
		httpContexts.put(obj, httpContext);
	}

	public static void remove(Object obj) {
		httpContexts.remove(obj);
	}

	public static HttpContext getContext(Object obj) {
		return httpContexts.get(obj);
	}

	public static String getContextPath() {
		return ActionContext.basePath;
	}
	
	public static String getApplicationFilePath(){
		return ActionContext.filePath;
	}
	
	public static Map<String,Action> getAction(String namespace){
		return actions.get(namespace);
	}
}
